package handler

import (
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"strconv"
	"video-manager/models"
)

func UpLoad(c *gin.Context) {
	file, _ := c.FormFile("file")
	filename := uuid.NewString() + ".png"
	path := "static/" + filename
	// 上传文件至指定的完整文件路径
	err := c.SaveUploadedFile(file, "./"+path)
	URL := "http://127.0.0.1:8000/" + path
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "文件上传失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "文件上传成功",
			"URL":  URL,
		})
		return
	}

}
func DeleteVideo(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))

	err := models.DB.Delete(&models.Video{}, "id=?", id).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "删除成功",
		})
		return
	}
}
func GetVideoById(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))
	var list models.Video
	models.DB.Where("id=?", id).Find(&list)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"list": list,
	})
	return
}

func VideoList(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var video []models.Video
	models.DB.Offset(offset).Limit(size).Find(&video)
	var total int64
	models.DB.Model(&models.Video{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  video,
		"total": total,
	})
	return
}

func CreateVideo(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	img := c.PostForm("img")
	if title == "" || content == "" || img == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	data := models.Video{
		Title:   title,
		Content: content,
		Img:     img,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "添加成功",
		})
		return
	}

}
